package online.xybh.qa.interceptor;

import online.xybh.qa.anno.StudentLogin;
import online.xybh.qa.anno.TeacherLogin;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: xybh
 * @Description:
 * @Date: Created in 23:46 2020/10/20
 * @Modified:
 */
public class AdminInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            StudentLogin studentLogin = handlerMethod.getMethod().getAnnotation(StudentLogin.class);
            TeacherLogin teacherLogin = handlerMethod.getMethod().getAnnotation(TeacherLogin.class);
            if (null != studentLogin) {
                Object user = request.getSession().getAttribute("user");
                if (user != null) {
                    return true;
                }
                String[] split = request.getRequestURL().toString().split("/");
                String backUrl = "/" + split[split.length - 1];
                response.sendRedirect(request.getContextPath() + "/login/student?backUrl=" + backUrl);
                return false;
            }
            if (null != teacherLogin) {
                Object user = request.getSession().getAttribute("user");
                if (user != null) {
                    return true;
                }
                String[] split = request.getRequestURL().toString().split("/");
                String backUrl = "/" + split[split.length - 1];
                response.sendRedirect(request.getContextPath() + "/login/teacher?backUrl=" + backUrl);
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
